package gdou.gym.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import gdou.gym.entity.People;
import gdou.gym.entity.User;
import gdou.gym.exception.ForbiddenException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j

public class TokenUtil {
    private static final String SIGN = "kjoinjeoifpo564456";
    public static final String ACCOUNT = "ACCOUNT";
    public static final String AUTHORIZATION = "AUTHORIZATION";
    public static final String LOGIN = "LOGIN";



    public static String getToken(People people) {
        JWTCreator.Builder claim = JWT.create().withClaim(ACCOUNT, people.getAccount());
        String sign;
        if (people instanceof User) {
            Boolean type = ((User) people).getType();
            claim.withClaim(AUTHORIZATION, type ? Authorization.STAFF.name() :
                    Authorization.STUDENT.name());
            claim.withClaim(LOGIN, Boolean.TRUE);
            sign = claim.sign(Algorithm.HMAC256(SIGN));
        } else {
            sign = claim.withClaim(AUTHORIZATION, Authorization.ADMIN.name())
                    .withClaim(LOGIN, Boolean.TRUE)
                    .sign(Algorithm.HMAC256(SIGN));
        }
        log.info("{}登陆了.....", people.getAccount());
        log.info("生成的token是：{}", sign);
        return sign;
    }

    public static String getAccount(String token) {
        return getData(token, ACCOUNT, String.class);
    }

    public static Authorization getAuthorization(String token) {
        String s = getData(token, AUTHORIZATION, String.class);
        return Authorization.valueOf(s);
    }

    public static Boolean checkToken(String token) {
        return getData(token, LOGIN, Boolean.class);
    }


    private static <T> T getData(String token, String field, Class<T> clazz) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SIGN)).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            return verify.getClaim(field).as(clazz);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new ForbiddenException();
        }
    }


}
